package de.mhu.mandalaui.bind;

import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import de.mhu.mandalaui.Component;
import de.mhu.mandalaui.Response;
import de.mhu.mandalaui.actions.Action;

public class Call {

	private Action action;
	private LinkedList<Element> parameters = new LinkedList<Element>();
	private boolean arrayParameter = true;
	private Component owner;
	
	public Call() {}
	
	public Call(Action action) {
		this(action,false);
	}
	
	public Call(Action action, boolean asArray, Element ... parameters) {
		setAction(action);
		setArrayParameter(asArray);
		if (parameters != null) {
			for (Element p : parameters) {
				getParameters().add(p);
			}
		}
	}
	
	public void startRender(Response response) {
		response.registerAttribute(action);
		action.startRender(response);
		if (parameters != null)
			for (Element p : parameters)
				p.startRender(response);
	}

	public void renderFunctionCall(PrintWriter out, boolean finishWithSemicolon) {
		if (action != null) {
			if (!action.needFunctionImplementation()) {

			} else {
				action.renderFunctionName(out);
				out.print("(");
				boolean first = true;
				if (arrayParameter)
					out.print("{");
				for (Element p : parameters) {
					if (!first)
						out.print(",");
					p.renderGet(out);
					first = false;
				}
				if (arrayParameter)
					out.print("}");
				out.print(")");
				if (finishWithSemicolon)
					out.print(";");
			}
		}
	}
	
	public Action getAction() {
		return action;
	}

	public void setAction(Action action) {
		this.action = action;
	}

	public List<Element> getParameters() {
		return parameters;
	}

	public boolean isArrayParameter() {
		return arrayParameter;
	}

	public void setArrayParameter(boolean arrayParameter) {
		this.arrayParameter = arrayParameter;
	}

	public void setOwner(Component owner) {
		this.owner = owner;
		if (action != null) action.setOwner(owner);
	}
	
	public Component getOwner() {
		return owner;
	}

}
